

package com.zdkj.subway.stm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.dto.UserInfo;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.entity.SwStApplyNetworkCheckPassengerAffairs;
import com.zdkj.subway.stm.entity.SwStConductorFareConsolidationNotice;
import com.zdkj.subway.stm.enums.CycleEnum;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.service.SwStConductorFareConsolidationNoticeService;
import com.zdkj.subway.stm.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 售票员票款合并结算通知
 *
 * @author chenbo
 * @date 2020-02-06 19:49:06
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstconductorfareconsolidationnotice")
@Api(value = "swstconductorfareconsolidationnotice", tags = "售票员票款合并结算通知管理")
public class SwStConductorFareConsolidationNoticeController {

    //数据来源线网
    private static final String DATA_SOUTCE_LINE = "0";
    //数据来源车站
    private static final String DATA_SOUTCE_STATION = "1";

    private final SwStConductorFareConsolidationNoticeService swStConductorFareConsolidationNoticeService;
    private final SystemUserService systemUserService;

    /**
     * 分页查询
     *
     * @param page                                 分页对象
     * @param swStConductorFareConsolidationNotice 售票员票款合并结算通知
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getPage(Page page, SwStConductorFareConsolidationNotice swStConductorFareConsolidationNotice, String[] dates) {
        String stationCode = SecurityUtils.getUser().getStationCode();
        String personLike = null;
        boolean flag = false;
        if (swStConductorFareConsolidationNotice.getMergePerson0() != null) {
            personLike = swStConductorFareConsolidationNotice.getMergePerson0();
            swStConductorFareConsolidationNotice.setMergePerson(null);
            flag = true;
        }
        String startDate = null;
        String endDate = null;
        boolean dateFlag = false;
        if (dates != null) {
            dateFlag = true;
            String s = dates[0];
            try {
                String decode = URLDecoder.decode(s, "utf-8");
                String[] split = decode.split("&");
                startDate = split[0].substring(6);
                endDate = split[1].substring(6);
                swStConductorFareConsolidationNotice.setNoticeTime(null);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (SecurityUtils.getUser().getBelongToLine()) {
            String finalPersonLike = personLike;
            boolean finalFlag = flag;
            boolean finalDateFlag = dateFlag;
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            return R.ok(swStConductorFareConsolidationNoticeService
                    .page(page, Wrappers.query(swStConductorFareConsolidationNotice)
                            .lambda()
                            .and(i -> i.eq(SwStConductorFareConsolidationNotice::getDataSource, CycleEnum.FARE_TYPE_LINE.getCode())
                                    .and(finalFlag,j->j.eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike)
                                    .or().eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike))
                                    .between(finalDateFlag, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate, finalEndDate))
                                    .or(i -> i.eq(SwStConductorFareConsolidationNotice::getDataSource, CycleEnum.FARE_TYPE_STATION.getCode())
                                    .ne(SwStConductorFareConsolidationNotice::getNoticeStatus, CycleEnum.FARE_NOTICE_FAIL.getCode())
                                            .and(finalFlag,j->j.eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike)
                                    .or().eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike))
                                    .between(finalDateFlag, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate, finalEndDate))


                    ));
        } else {
            boolean finalFlag1 = flag;
            String finalPersonLike1 = personLike;
            boolean finalFlag2 = flag;
            String finalStartDate1 = startDate;
            String finalEndDate1 = endDate;
            return R.ok(swStConductorFareConsolidationNoticeService
                    .page(page, Wrappers.query(swStConductorFareConsolidationNotice)
                            .lambda().and(i -> i.eq(SwStConductorFareConsolidationNotice::getStationCode, stationCode)
                                    .and(finalFlag1,j->j.eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike1)
                                    .or().eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike1))
                                    .between(finalFlag2, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate1, finalEndDate1)
                            .eq(SwStConductorFareConsolidationNotice::getDataSource, DATA_SOUTCE_STATION))
                            .or(i -> i.ne(SwStConductorFareConsolidationNotice::getNoticeStatus, CycleEnum.FARE_NOTICE_FAIL.getCode())
                                    .eq(SwStConductorFareConsolidationNotice::getDataSource, DATA_SOUTCE_LINE)
                                    .and(finalFlag1,j->j.eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike1)
                                    .or().eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike1))
                                    .between(finalFlag2, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate1, finalEndDate1))
                    ));
        }
    }


    @GetMapping("/export")
    @SysLog("导出售票员票款合并结算通知")
    @PreAuthorize("@pms.hasPermission('stm_swstconductorfareconsolidationnotice_export')")
    public void exportExcel(Page page, SwStConductorFareConsolidationNotice swStConductorFareConsolidationNotice, String[] dates,
                            HttpServletResponse response) throws IOException {
        String stationCode = SecurityUtils.getUser().getStationCode();
        List<SwStConductorFareConsolidationNotice> list;
        String personLike = null;
        boolean flag = false;
        if (swStConductorFareConsolidationNotice.getMergePerson0() != null) {
            personLike = swStConductorFareConsolidationNotice.getMergePerson0();
            swStConductorFareConsolidationNotice.setMergePerson(null);
            flag = true;
        }
        String startDate = null;
        String endDate = null;
        boolean dateFlag = false;
        if (dates != null) {
            dateFlag = true;
            String s = dates[0];
            try {
                String decode = URLDecoder.decode(s, "utf-8");
                String[] split = decode.split("&");
                startDate = split[0].substring(6);
                endDate = split[1].substring(6);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (SecurityUtils.getUser().getBelongToLine()) {
            String finalPersonLike = personLike;
            boolean finalFlag = flag;
            boolean finalDateFlag = dateFlag;
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            list = swStConductorFareConsolidationNoticeService
                    .pageMapper(page, Wrappers.query(swStConductorFareConsolidationNotice)
                            .allEq(SelMapUtils.getSwStConductorFareConsolidationNoticeMap(swStConductorFareConsolidationNotice))
                            .lambda()
                            .and(i -> i.eq(SwStConductorFareConsolidationNotice::getDataSource, CycleEnum.FARE_TYPE_LINE.getCode())
                                    .and(finalFlag,j->j.eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike)
                                    .or().eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike))
                                    .between(finalDateFlag, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate, finalEndDate)
                                    )
                            .or(i -> i.eq(SwStConductorFareConsolidationNotice::getDataSource, CycleEnum.FARE_TYPE_STATION.getCode())
                                    .ne(SwStConductorFareConsolidationNotice::getNoticeStatus, CycleEnum.FARE_NOTICE_FAIL.getCode())
                                    .and(finalFlag,j ->j.eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike)
                                            .or().eq(finalFlag, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike))
                                    .between(finalDateFlag, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate, finalEndDate))


                    ).getRecords();
        } else {
            boolean finalFlag1 = flag;
            String finalPersonLike1 = personLike;
            boolean finalFlag2 = flag;
            String finalStartDate1 = startDate;
            String finalEndDate1 = endDate;
            list = swStConductorFareConsolidationNoticeService
                    .pageMapper1(page, Wrappers.query(swStConductorFareConsolidationNotice)
                            .lambda().and(i -> i.eq(SwStConductorFareConsolidationNotice::getStationCode, stationCode)
                                    .and(finalFlag1,j->j.eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike1)
                                    .or().eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike1))
                                    .between(finalFlag2, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate1, finalEndDate1)
                            .eq(SwStConductorFareConsolidationNotice::getDataSource, DATA_SOUTCE_STATION))
                            .or(i -> i.ne(SwStConductorFareConsolidationNotice::getNoticeStatus, CycleEnum.FARE_NOTICE_FAIL.getCode())
                                    .eq(SwStConductorFareConsolidationNotice::getDataSource, DATA_SOUTCE_LINE)
                                    .and(finalFlag1,j->j.eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson, finalPersonLike1)
                                    .or().eq(finalFlag1, SwStConductorFareConsolidationNotice::getMergePerson2, finalPersonLike1))
                                    .between(finalFlag2, SwStConductorFareConsolidationNotice::getNoticeTime, finalStartDate1, finalEndDate1))
                    ).getRecords();
        }
        String fileName = URLEncoder.encode("售票员票款合并结算通知", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStConductorFareConsolidationNotice.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("售票员票款合并结算通知").doWrite(list);
    }

    /**
     * 通过id批量删除售票员票款合并结算通知
     *
     * @param list list
     * @return R
     */
    @ApiOperation(value = "通过id批量删除售票员票款合并结算通知", notes = "通过id批量删除售票员票款合并结算通知")
    @SysLog("通过id批量删除售票员票款合并结算通知")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_fare_consolidation_notice_delBatch')")
    public R removeByIds(@RequestBody List<Integer> list) {
        return R.ok(swStConductorFareConsolidationNoticeService.removeByIds(list));
    }

    /**
     * 通过id查询售票员票款合并结算通知
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStConductorFareConsolidationNoticeService.getById(id));
    }

    /**
     * 新增售票员票款合并结算通知
     *
     * @param swStConductorFareConsolidationNotice 售票员票款合并结算通知
     * @return R
     */
    @ApiOperation(value = "新增售票员票款合并结算通知", notes = "新增售票员票款合并结算通知")
    @SysLog("新增售票员票款合并结算通知")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_swstconductorfareconsolidationnotice_add')")
    public R save(@RequestBody SwStConductorFareConsolidationNotice swStConductorFareConsolidationNotice) {
        SwStConductorFareConsolidationNotice defaultObj = ObjectValueUtils
                .getDefaultObj(SwStConductorFareConsolidationNotice.class);
        BeanUtil.copyProperties(swStConductorFareConsolidationNotice, defaultObj,
                CopyOptions.create().setIgnoreProperties(BeanPropertyUtils.
                        getNullAndEmptyPropertyNames(swStConductorFareConsolidationNotice)));
        if (SecurityUtils.getUser().getBelongToLine()) {
            defaultObj.setDataSource(DATA_SOUTCE_LINE);
        } else {
            defaultObj.setDataSource(DATA_SOUTCE_STATION);
        }
        return R.ok(swStConductorFareConsolidationNoticeService.save(defaultObj));
    }

    /**
     * 批量通知
     *
     * @param swStConductorFareConsolidationNotice 售票员票款合并结算通知
     * @return R
     */
    @ApiOperation(value = "售票员票款合并结算通知", notes = "售票员票款合并结算通知")
    @SysLog("售票员票款合并结算通知")
    @PutMapping("noticeBatch")
    @PreAuthorize("@pms.hasPermission('stm_swstconductorfareconsolidationnotice_noticeBatch')")
    public R noticeBatch(@RequestBody List<SwStConductorFareConsolidationNotice> swStConductorFareConsolidationNotice) {
        for (SwStConductorFareConsolidationNotice s : swStConductorFareConsolidationNotice) {
            if(s.getDataSource().equals(CycleEnum.FARE_TYPE_LINE.getCode())&&SecurityUtils.getUser().getBelongToLine()){
                s.setNoticeStatus(CycleEnum.FARE_NOTICE_SUC.getCode());
                s.setNoticeType(CycleEnum.FARE_TYPE_LINE.getCode());
            }
            if(s.getDataSource().equals(CycleEnum.FARE_TYPE_STATION.getCode())&&!SecurityUtils.getUser().getBelongToLine()){
                s.setNoticeStatus(CycleEnum.FARE_NOTICE_2.getCode());
                s.setNoticeType(CycleEnum.FARE_TYPE_STATION.getCode());
            }

            s.setNoticeTime(LocalDateTime.now());
        }
        return R.ok(swStConductorFareConsolidationNoticeService.updateBatchById(swStConductorFareConsolidationNotice));
    }

    /**
     * 修改售票员票款合并结算通知
     *
     * @param swStConductorFareConsolidationNotice 售票员票款合并结算通知
     * @return R
     */
    @ApiOperation(value = "修改售票员票款合并结算通知", notes = "修改售票员票款合并结算通知")
    @SysLog("修改售票员票款合并结算通知")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_swstconductorfareconsolidationnotice_edit')")
    public R updateById(@RequestBody SwStConductorFareConsolidationNotice swStConductorFareConsolidationNotice) {
        return R.ok(swStConductorFareConsolidationNoticeService.updateById(swStConductorFareConsolidationNotice));
    }

    /**
     * 通过id删除售票员票款合并结算通知
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除售票员票款合并结算通知", notes = "通过id删除售票员票款合并结算通知")
    @SysLog("通过id删除售票员票款合并结算通知")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_swstconductorfareconsolidationnotice_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStConductorFareConsolidationNoticeService.removeById(id));
    }


}
